﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using DocumentInterchange.Filters;
using DocumentInterchange.Models;

namespace DocumentInterchange.Controllers
{
	[Authorize]
	[InitializeSimpleMembership]
	public class AccountController : Controller
	{
		//
		// GET: /Account/Login

		[AllowAnonymous]
		public ActionResult Login(string returnUrl)
		{
			ViewBag.ReturnUrl = returnUrl;
			return View();
		}

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                return RedirectToAction("Input", "Home");
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "Имя или пароль были введены неверно.");
            return View(model);
        }

        [AllowAnonymous]
		public ActionResult PersonalPage()
		{
			if (ModelState.IsValid)
			{
				// Attempt to register the user
				try
				{
                    WebMatrix.WebData.ExtendedMembershipProvider p;
					WebSecurity.CreateUserAndAccount("admin", "admin");
					WebSecurity.Login("admin", "admin");
					return RedirectToAction("Input", "Home");
				}
				catch (MembershipCreateUserException e)
				{
					ModelState.AddModelError("", "Error");
				}
			}

			return View();
		}		

		//
		// POST: /Account/LogOff

		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult LogOff()
		{
			WebSecurity.Logout();

			return RedirectToAction("Index", "Home");
		}

		private ActionResult RedirectToLocal(string returnUrl)
		{
			if (Url.IsLocalUrl(returnUrl))
			{
				return Redirect(returnUrl);
			}
			else
			{
				return RedirectToAction("Index", "Home");
			}
		}

    }
}
